from flask import jsonify
from flask.views import MethodView
from app.models.user import User
from ..auth import generate_token
from ..forms import TokenForm


class AuthTokenAPI(MethodView):
    def post(self):
        form = TokenForm()
        if form.validate_on_submit():
            user = User.query.filter_by(username=form.username.data).first()

            if user is None or not user.validate_password(form.password.data):
                return jsonify(success=False, message="账号或密码错误!")

            if user.status != 100:
                return jsonify(success=False, message="账号未审核！")

            token, expiration = generate_token(user)

            response = jsonify({
                'success': True,
                'data': {
                    'access_token1': token,
                    'expiration': expiration
                }
            })
            response.headers['Cache-Control'] = 'no-store'
            response.headers['Pragma'] = 'no-cache'
            return response

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()}
            return jsonify(success=False, message=message)
